<?php

namespace app\middleware;

use app\helper\Config;
use app\model\User;
use Exception;
use Shopwwi\WebmanAuth\Facade\JWT as JwtFace;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class SellTokenAuth implements MiddlewareInterface
{

    protected Config $configRe;


    public function __construct()
    {
        $this->configRe = Config::getInstance();
    }


    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param callable $handler
     * @return Response
     * @throws Exception
     */
    public function process(Request $request, callable $handler): Response
    {

        if (empty($request->header('SellSign'))) {
            throw new Exception('请先验证身份', 501);
        }

        try {
            $tokenInfo = JwtFace::verify($request->header('SellSign'));
        } catch (Exception) {
            throw new Exception('请先验证身份', 501);
        }

        if (empty($tokenInfo)) {
            throw new Exception('请先验证身份', 501);
        }

        if ($tokenInfo->iss !== config('plugin.shopwwi.auth.app.jwt.iss')) {
            throw new Exception('身份验证令牌无效', 501);
        }
        if ($tokenInfo->guard !== 'user') {
            throw new Exception('身份验证令牌无效', 501);
        }
        if ($tokenInfo->iat > time()) {
            throw new Exception('身份验证令牌无效', 501);
        }
        if ($tokenInfo->exp <= time()) {
            throw new Exception('身份验证令牌无效', 501);
        }
        if ($tokenInfo->extend->scene !== 'SELL') {
            throw new Exception('身份验证令牌无效', 501);
        }

        try {
            // 登录用户验证
            $user = User::query()->where('ulid', $tokenInfo->extend->ulid)->where('state', 1)->first();
            if (!$user) {
                throw new Exception('请重新登录', 999);
            }
        } catch (Exception) {
            throw new Exception('请重新登录', 999);
        }

        return $handler($request);
    }

}